import React, { FC, useEffect, useMemo, useState } from 'react'
import Header from '@/components/home/header'
import { initCurrendStdAdd } from '@/store/address'
import { useNavigate } from 'react-router-dom'
import confirm from '@/components/home/confirm'
import { useAppSelector, useAppDispatch } from '@/store'
import {
  selectPayParam,
  selectPayPrice,
  selectPayTimeSpan,
  setPayTimeSpan,
  setPayParam,
  setLocalstorage,
  setStartPayTime,
} from '@/store/payCenter'
import { format } from '@/utils/date'
import { Countdown, CountdownTime } from '@/store/countdown'
import { cannelPay, getOrderPayStatus } from '@/api/orderConfirm'
import { EPaySimpleCode } from '@/types/payCenter'
import { orderPay } from '@/api/orderConfirm'
import { Dialog, Toast } from 'antd-mobile'
import { getQueryVariable } from '@/utils/http'
const W8 = 8 * 3600 * 1000
/**
 * 支付状态页面
 */
const welfare: FC<{}> = () => {
  const navigate = useNavigate()
  const dispatch = useAppDispatch()
  const payParam = useAppSelector(selectPayParam)
  const prise = useAppSelector(selectPayPrice)
  const selectStr = 'text-orange-FF3627 icon-icon_selected'
  const PayTimeSpan = useAppSelector(selectPayTimeSpan)
  const [pay, selectPay] = useState<EPaySimpleCode>(EPaySimpleCode.WEIXIN)
  const [timeSpan, setTimeSpan] = useState<string>('')
  const orderNum = getQueryVariable('orderNum') as string
  const XBusinesslineId = getQueryVariable('X-Businessline-Id') as string
  if (!orderNum && !XBusinesslineId) {
    navigate('/pay/payEmpty')
  }
  const countdown = useMemo(
    () =>
      new Countdown(PayTimeSpan, {
        /**上下文 */
        content: null,
        fn: {
          start: () => {
            if (PayTimeSpan > 0) {
              setTimeSpan(format(new Date(PayTimeSpan), 'mm:ss'))
              dispatch(setPayParam({ orderNum: orderNum }))
            } else {
              navigate('/payLoseEfficacy')
            }
            // console.log(111)
          },
          every1s: (time: CountdownTime) => {
            //局部
            setTimeSpan(format(new Date(PayTimeSpan - time), 'mm:ss'))
            dispatch(setPayTimeSpan(PayTimeSpan - time))
            // setTimeSpan(format(new Date(time), 'mm:ss'))
            if (orderNum) {
              getOrderPayStatus(orderNum).then((res) => {
                if (res) {
                  countdown?.reset()
                  navigate('/paySuccess')
                  // location.href = '/paySuccess'
                }
              })
            }
          },
          finish: () => {
            navigate('/payLoseEfficacy')
          },
        },
      }),
    [orderNum],
  )
  useEffect(() => {
    countdown?.startTime()
    dispatch(setLocalstorage())
    return () => {
      countdown?.reset()
      countdown?.clearInterval()
    }
  }, [countdown])
  /**回退拦截 */
  const state = {
    title: 'title',
    url: '',
  }
  const browserBack = () => {
    confirm(
      '真的要取消订单吗？',
      async () => {
        const res = await cannelPay({
          orderNum: orderNum,
          'X-Businessline-Id': parseInt(XBusinesslineId),
        })
        dispatch(setPayTimeSpan(-1))
        if (res.status != 1) {
          Toast.show(res.data)
        } else {
          navigate(-1)
        }
      },
      () => {
        window.history.pushState({}, 'status', window.location.href)
      },
      '取消支付',
      '继续支付',
    )
  }
  useEffect(() => {
    if (!history.state || (history.state && history.state.title !== 'status')) {
      const state = {
        title: 'status',
        url: '',
      }
      window.history.pushState(state, 'status', window.location.href)
      window.addEventListener('popstate', browserBack)
    }

    return () => {
      window.removeEventListener('popstate', browserBack, false)
    }
  }, [])
  //https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=wx141421524184578a811adb697f164e0000&package=553572278
  //initCurrendStdAdd
  return (
    <div className="w-full h-full bg-white ">
      <Header
        cb={() => {
          navigate(-1)
        }}
        headerText={'收银台'}
      ></Header>
      <div className=" pt-r2.2 pb-r2.4 pl-r1.2 pr-r1.2 h-r14.5 w-full text-center ">
        <div>
          {/* <p className=" block text-r1.2 leading-r1.7 pt-r1.0  mb-r0.8">
            订单号：{payParam.orderNum}
          </p> */}
          <p className="block text-r1.2 leading-r1.7 text-gray-666666 ">
            剩余支付之间:
            <em className="pl-r0.5 pr-r0.5 text-r1.2 font-bold not-italic  ">{timeSpan}</em>
          </p>
        </div>
        <span className=" text-r2.0 ">
          <span>￥</span>
          <span className=" text-r3.2">{prise}</span>
        </span>
      </div>
      <div className=" clear-both  border border-white-F3F3F4  scale-y-50  "></div>
      <div>
        <div>
          <div className="flex  pl-r1.8 pr-r1.8 h-r8.0 leading-r8.0">
            <div className=" flex-1.125  text-r2.2">
              <i className="iconfont icon-icon_weixin text-green-07C160 "></i>
            </div>
            <div className=" flex-1.7 flex flex-col justify-center">
              <div className="leading-r2.0 ">
                <span className="text-r1.4 text-gray-212831">微信支付</span>
              </div>
            </div>
            <span
              className=" flex-1.125 text-right"
              onClick={() => {
                selectPay(EPaySimpleCode.WEIXIN)
              }}
            >
              <i
                className={
                  'w-r2.0 h-r2.0 text-r1.6 iconfont  ' +
                  (pay === EPaySimpleCode.WEIXIN ? selectStr : ' icon-icon_unselected')
                }
              ></i>
            </span>
          </div>

          <div className="flex  pl-r1.8 pr-r1.8 h-r8.0 leading-r8.0">
            <div className=" flex-1.125  text-r2.2">
              <i className="iconfont icon-icon_alipay text-blue-02A9F1  "></i>
            </div>
            <div className=" flex-1.7 flex flex-col justify-center">
              <div className="leading-r2.0 ">
                <span className="text-r1.4 text-gray-212831">支付宝</span>
              </div>
              {/* <p className="leading-r2.0 text-gray-868D9B">亿万用户的选择，更快更安全</p> */}
            </div>
            <span
              className=" flex-1.125 text-right"
              onClick={() => {
                selectPay(EPaySimpleCode.ZHIFUBAO)
              }}
            >
              <i
                className={
                  'w-r2.0 h-r2.0 text-r1.6 iconfont ' +
                  (pay === EPaySimpleCode.ZHIFUBAO ? selectStr : ' icon-icon_unselected')
                }
              ></i>
            </span>
          </div>
        </div>
      </div>
      <div className="w-full fixed bottom-r2.2 ">
        <span
          onClick={async () => {
            const res = await orderPay({
              payCode: pay,
              isUseBalance: payParam.isUseBalance!,
              orderNum: payParam.orderNum!,
            })
            if (res.sign === 1) {
              location.href = res.msg //to du
            } else {
              navigate('/payLoseEfficacy')
            }
          }}
          className=" shadow-bs4 relative left-1/2 transform -translate-x-1/2 text-r1.5 leading-r4.4 h-r4.4 w-r31.1  text-white leading-r4.0 rounded-r2.0  bg-gradient-to-r from-orange-FF664F to-orange-FF3627 inline-block text-center "
        >
          立即支付
        </span>
      </div>
    </div>
  )
}

export default welfare
